package controllers;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import models.Account;
import models.Account_role;
import models.Menu;
import models.Permission;
import models.Role;
import models.Role_menu_permission;

public class AuthorHelper {
	public static boolean canViewTable(String user, String menu_name) {
		if (isAdmin(findAccount(user))) {
			return true;
		} else {
			
		}
		return true;
	}
	
	public static boolean isInRoleGroup(String uname, String rnames) {	
		if (rnames.isEmpty()) {
			return true;
		} else if (rnames.equals("-1")) {
			return false;
		}
		
		String [] rnt = rnames.split(",");
		Account a = findAccount(uname);
		if (isAdmin(a)) {
			return true;
		} else {
			List<Role> roles = getRoles(a);
			for(String rname : rnt) {
				int rid = Integer.parseInt(rname);
				for(Role r: roles) {
					if (r.getId().equals(rid)) {
						return true;
					}
				}				
			}
		}
		return false;
	}
	
	public static Account findAccount(String name) {
		return Account.findByName(name);
	}
	
	public static boolean isAdmin(Account user) {
		List<Role> roles = getRoles(user);
    	for(Role role : roles) {
    		if (role.getName().equalsIgnoreCase("超级用户")) {
    			return true;
    		}
    	}
    	return false;
    }
	
	public static boolean canDo(String user, String table, String permission) {
		Account a = findAccount(user);
		if (isAdmin(a)) {
			return true;
		}
		List<Role> roles =  getRoles(a);
		for(Role role: roles) {
			List<Role_menu_permission> rmps = getPermissions(role);
			for(Role_menu_permission rmp: rmps) {
				Menu m = Menu.findById(rmp.getMenu().getId());
				if (!table.equalsIgnoreCase(m.getName())) {
					continue;
				}
				Permission p = Permission.findById(rmp.getPermission().getId());
				if (p.getName().equalsIgnoreCase(permission)) {
					return true;
				}
			}
		}
		return false;
	}
	
	private static List<Role> getRoles(Account user) {
		List<Role> roles = new ArrayList<Role>();
		List<Account_role> ars = Account_role.find.where().eq("account.id", user.getId()).findList();
		for(Account_role ar : ars) {
    		Role role = Role.findById(ar.getRole().getId());
    		roles.add(role);
		}
		return roles;
	}
	
	private static List<Role_menu_permission> getPermissions(Role role) {
		List<Role_menu_permission> rmps = Role_menu_permission.find.where().eq("role.id", role.getId()).findList();
		return rmps;
	}
	
	
}
